package com.maint.g


import com.maint.g.utils.BuildConfig
import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.maint.g.utils.SPUtil
import com.rokid.glass.arworkflow.media.record.logE
import com.rokid.security.glass3.sdk.api.GlassSDK
import com.rokid.security.glass3.sdk.api.engine.bean.EngineParam
import com.rokid.security.glass3.sdk.api.message.listener.IMessageListener
// 移除错误的导入

import android.media.AudioFormat
import android.media.AudioManager
import android.media.AudioTrack
import com.maint.g.utils.AudioStreamManager
import java.nio.ByteBuffer

class MainActivity : AppCompatActivity() {
    private val OVERLAY_PERMISSION_REQ_CODE = 1001  // 悬浮窗权限请求码
    private val CAMERA_PERMISSION_REQ_CODE = 1002   // 相机权限请求码
    private val WIFI_PERMISSION_REQ_CODE = 1004     // WiFi权限请求码（Android 10+）
    private val REQUEST_CODE_NEARBY_WIFI = 1005
    private val REQUEST_RECORD_AUDIO_PERMISSION = 1006
    private val REQUEST_CODE_STORAGE_PERMISSION = 1007
    
    private val TAG = "MainActivity::"


    private lateinit var audioStreamManager: AudioStreamManager
    private lateinit var audioMessageHandler: AudioStreamManager.AudioMessageHandler


    // SDK服务初始化
    private val mAbsSecurityEngineService by lazy {
        GlassSDK.getGlassEngineService()
    }

    // 消息服务
    private val mAbsGlassMessageService by lazy {
        GlassSDK.getGlassMessageService()
    }
    
    // 语音播报服务
    private val mAbsGlassTtsService by lazy {
        GlassSDK.getGlassTtsService()
    }
    
    private var isGlassConnected = false
    
    // 用于显示接收到的消息并在10秒后隐藏
    private lateinit var tvText: TextView
    private var hideMessageHandler: android.os.Handler? = null
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        
        // 初始化UI组件
        initUI()
        hideMessageHandler = android.os.Handler()
        
        // 获取权限
        getPermission()
        
        // 初始化SDK
        initGlassSDK()
        
        // 初始化眼镜引擎
        initGlassEngine()

        // 初始化音频流管理器
        initAudioStreamManager()

        // 设置消息监听器
        mAbsGlassMessageService?.addMessageListener(messageListener)
    }
    
    private fun initUI() {
        // 初始化用于显示临时消息的TextView
        tvText = findViewById(R.id.tv_text)
        
        // 初始状态下隐藏tv_text
        tvText.visibility = View.GONE

//        findViewById<View>(R.id.btn_stop_video).setOnClickListener {
//            stopVideoStream()
//        }
    }
    
    private fun initGlassSDK() {
        // 直接使用BuildConfig中的serverId
        val serverId = BuildConfig.SDK_SERVER_ID
        val param = EngineParam(serverId, "", "", arrayListOf())
        
        Log.e(TAG, "开始初始化SDK，ServerId: $serverId")
        mAbsSecurityEngineService.initSDK(param) {
            Log.e(TAG, "SDK初始化结果: ${it.isSuccess}")
            if (it.isSuccess) {
                Log.e(TAG, "SDK初始化成功")
            } else {
                Log.e(TAG, "SDK初始化失败: 初始化未成功")
            }
        }
    }
    
    // 初始化眼镜引擎
    private fun initGlassEngine() {
        Log.e(TAG, "初始化眼镜引擎")
        // 这里不需要单独启动WifiP2P服务，SDK会自动处理连接
    }


    // 初始化音频流管理器
    private fun initAudioStreamManager() {
        audioStreamManager = AudioStreamManager(this)
        audioStreamManager.initialize()
        audioMessageHandler = audioStreamManager.createAudioMessageHandler()
        Log.d(TAG, "音频流管理器初始化完成")
    }
    private fun speakText(content: String) {
        try {
            mAbsGlassTtsService?.doSpeechTts(content)
            Log.e(TAG, "开始语音播报: $content")
        } catch (e: Exception) {
            Log.e(TAG, "语音播报失败: ${e.message}")
        }
    }
    
    // 取消语音播报
    private fun cancelTTS() {
        try {
            mAbsGlassTtsService?.doCancelTts()
        } catch (e: Exception) {
            Log.e(TAG, "取消语音播报失败: ${e.message}")
        }
    }
    
    // 开始视频流传输
    private fun startVideoStream() {
        try {
            mAbsGlassMessageService?.sendVideoStreamData()
            Log.e(TAG, "开始发送视频流")
            speakText("开始发送视频流")
        } catch (e: Exception) {
            Log.e(TAG, "发送视频流失败: ${e.message}")
        }
    }
    
    // 停止视频流传输
    private fun stopVideoStream() {
        try {
            mAbsGlassMessageService?.stopVideoStreamData()
            Log.e(TAG, "停止发送视频流")
            Toast.makeText(this, "停止发送视频流", Toast.LENGTH_SHORT).show()
        } catch (e: Exception) {
            Log.e(TAG, "停止视频流失败: ${e.message}")
        }
    }
    
    // 消息监听器
    private var messageListener = object : IMessageListener {
        // 文本消息处理
        override fun onP2PTextMessage(msg: String) {
            super.onP2PTextMessage(msg)
            Log.d(TAG, "收到文本消息: $msg")
//            updateMessageOnUI(msg)
            
            // 显示消息到tv_text并设置10秒后隐藏
            showMessageTemporarily(msg)

            // 当收到消息时，可以认为设备已连接
            if (!isGlassConnected) {
                updateConnectionStatus(true)
            }
            if (msg == "开始") {
                startVideoStream()
            } else if (msg == "停止") {
                stopVideoStream()
            } else if (msg == "操作完毕") {
                mAbsGlassMessageService?.sendTextMessageByP2P("close")
                stopVideoStream()
            }
        }

        override fun onAudioStream(buffer: ByteBuffer) {
            super.onAudioStream(buffer)
            Log.d(TAG, "收到音频流数据${buffer}")
            // 处理音频数据，例如播放或存储
            audioStreamManager.processAudioData(buffer)
        }
    }
    
    // 更新UI显示消息（已改为使用showMessageTemporarily方法）
    
    // 权限申请
    fun getPermission() {
        // 检查录音权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO)
            != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(
                this,
                arrayOf(Manifest.permission.RECORD_AUDIO),
                REQUEST_RECORD_AUDIO_PERMISSION
            )
        }
        
        // 检查相机权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
            != PackageManager.PERMISSION_GRANTED
        ) {
            requestCameraPermission(this as Activity)
            return
        } else {
            Log.e(TAG, "相机权限已拥有")
        }
        
        // 已移除蓝牙权限检查，专注于WiFiP2P功能
        
        // 检查WiFi权限（Android 10+ 需要定位权限）
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            if (this.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED
            ) {
                requestWifiPermission(this)
                return
            } else {
                Log.e(TAG, "WiFi权限已拥有")
            }
        }
        
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (checkSelfPermission(Manifest.permission.NEARBY_WIFI_DEVICES) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(arrayOf(Manifest.permission.NEARBY_WIFI_DEVICES), REQUEST_CODE_NEARBY_WIFI)
                Log.e(TAG, "附近 Wi-Fi 设备权限未拥有")
                return
            } else {
                Log.e(TAG, "附近 Wi-Fi 设备权限已拥有")
            }
        }
        
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(
                this,
                arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
                REQUEST_CODE_STORAGE_PERMISSION
            )
        }
    }
    
    private fun requestCameraPermission(activity: Activity) {
        ActivityCompat.requestPermissions(
            activity,
            arrayOf(Manifest.permission.CAMERA),
            CAMERA_PERMISSION_REQ_CODE
        )
    }
    
    // WiFi权限
    private fun requestWifiPermission(activity: Activity) {
        ActivityCompat.requestPermissions(
            activity,
            arrayOf(
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_WIFI_STATE // 如需操作WiFi
            ),
            WIFI_PERMISSION_REQ_CODE
        )
    }
    
    // 蓝牙权限请求方法已移除
    
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        
        when (requestCode) {
            CAMERA_PERMISSION_REQ_CODE -> {
                if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
                    Log.e(TAG, "相机权限获取成功")
                } else {
                    Log.e(TAG, "相机权限获取失败")
                    Toast.makeText(this, "相机权限被拒绝，部分功能可能无法使用", Toast.LENGTH_SHORT).show()
                }
            }
            // 蓝牙权限结果处理已移除
            REQUEST_RECORD_AUDIO_PERMISSION -> {
                if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
                    Log.e(TAG, "录音权限获取成功")
                } else {
                    Log.e(TAG, "录音权限获取失败")
                    Toast.makeText(this, "录音权限被拒绝，无法使用语音功能", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }
    
    override fun onDestroy() {
        super.onDestroy()

        
        // 释放音频流管理器资源
        audioStreamManager.release()

        // 清理资源
        mAbsGlassMessageService?.removeMessageListener(messageListener)
        
        // 移除隐藏消息的Handler回调
        hideMessageHandler?.removeCallbacksAndMessages(null)
        
        // 移除WifiP2P相关清理代码
        
        mAbsSecurityEngineService.destroy()

        stopVideoStream()
    }
    
    override fun onResume() {
        super.onResume()
        window.addFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
        
        // 检查WifiP2P连接状态
        checkWifiP2PConnection()
    }
    
    private fun checkWifiP2PConnection() {
        Log.e(TAG, "检查WiFi P2P连接状态")
        
        // 尝试通过发送测试消息来验证连接
        try {
            mAbsGlassMessageService?.let {
                Log.e(TAG, "消息服务已初始化，尝试检查连接")
                // 这里可以添加实际的连接检查逻辑，例如发送心跳包等
            }
        } catch (e: Exception) {
            Log.e(TAG, "检查连接时出错: ${e.message}")
        }
    }
    
    private fun updateConnectionStatus(isConnected: Boolean) {
        isGlassConnected = isConnected
        if (isConnected) {
            speakText("眼镜已连接到移动设备")
            Log.e(TAG, "设备已连接")
        } else {
            Log.e(TAG, "等待设备连接")
        }
    }
    
    // 显示消息并设置10秒后隐藏
    private fun showMessageTemporarily(message: String) {
        runOnUiThread {
            // 先移除之前可能存在的隐藏消息的Runnable
            hideMessageHandler?.removeCallbacksAndMessages(null)
            
            // 显示消息
            tvText.text = message
            tvText.visibility = View.VISIBLE
            Log.d(TAG, "显示临时消息: $message")
            
            // 设置10秒后隐藏消息
            hideMessageHandler?.postDelayed({ 
                runOnUiThread {
                    tvText.visibility = View.GONE
                    Log.d(TAG, "临时消息已隐藏")
                }
            }, 10000) // 10000毫秒 = 10秒
        }
    }
    
    override fun onPause() {
        super.onPause()
        window.clearFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
    }

}